<template>
  <el-dialog
    :visible="dialogVisible"
    :close-on-click-modal="false"
    :title="elDialogTitle"
    width="550px"
    top="5%"
    :before-close="cancelClose"
  >
    <el-form ref="addform" :model="addform" :rules="rules" label-width="120px">
      <el-form-item label="会议名称：" prop="meetingName">
        <el-input v-model="addform.meetingName" clearable></el-input>
      </el-form-item>

      <el-form-item label="会议类型：" prop="type">
        <el-select v-model="addform.type" filterable clearable>
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="会议时间：" prop="meetingTime">
        <el-date-picker
          v-model="addform.meetingTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm"
          format="yyyy-MM-dd HH:mm"
          placeholder="请选择"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="描述：" prop="describe">
        <el-input
          type="textarea"
          v-model="addform.describe"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="参会人：" prop="joinUserAccount">
        <el-select
          v-model="addform.joinUserAccount"
          filterable
          remote
          multiple
          :remote-method="remoteSearch"
          placeholder="请搜索选择人员"
          @change="joinUserChange"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label + '---' + item.value"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="会议负责人：" prop="masterUserAccount">
        <el-select
          placeholder="请搜索选择人员"
          v-model="addform.masterUserAccount"
          filterable
          remote
          multiple
          :remote-method="remoteSearch"
          @change="masterUserChange"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label + '---' + item.value"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="cancelClose">取 消</el-button>
      <el-button type="primary" @click="sureAdd">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  add,
  edit,
  findUserByOrgId,
  copyMeetingConfig
} from '@/apis/meetingConfiguration.js'

export default {
  data() {
    return {
      orgGrade: [1, 2, 3, 4, 5, 6, 7, 8, 9],
      orgList: [],
      userList: [],
      addform: {
        masterUserAccount: [],
        joinUserAccount: [],
        meetingName: '',
        type: '',
        meetingTime: '',
        describe: '',
        masterUserName: [],
        joinUserName: []
      },
      typeList: [
        {
          value: '0',
          label: '月度会议'
        },
        {
          value: '1',
          label: '季度会议'
        },
        {
          value: '2',
          label: '年度会议'
        },
        {
          value: '3',
          label: '临时会议'
        }
      ],
      elDialogTitle: '新增',
      dialogVisible: false,
      loadUser: false,
      rules: {
        meetingName: [
          { required: true, message: '请填写会议名称！', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择会议类型！', trigger: 'change' }
        ],
        meetingTime: [
          { required: true, message: '请选择会议时间！', trigger: 'change' }
        ],
        joinUserAccount: [
          { required: true, message: '请搜索选择人员！', trigger: 'change' }
        ],
        masterUserAccount: [
          { required: true, message: '请搜索选择人员！', trigger: 'change' }
        ]
      },
      options: [], // 初始选项为空
      loadingUser: false, // 是否正在加载数据
      searchQuery: '' // 搜索查询字符串
    }
  },

  mounted() {},
  methods: {
    remoteSearch(query) {
      if (query !== '') {
        this.searchQuery = query
        this.fetchData()
      } else {
        this.options = [] // 清空选项
      }
    },
    fetchData() {
      if (this.loadingUser) return // 避免重复请求
      this.loadingUser = true
      findUserByOrgId({ userName: this.searchQuery })
        .then((response) => {
          this.options = response.data.map((item) => ({
            value: item.account,
            label: item.fullName
          }))
          this.loadingUser = false
        })
        .catch((error) => {
          console.error('搜索出错:', error)
          this.loadingUser = false
        })
    },
    joinUserChange() {
      let name = []
      this.options.forEach((item) => {
        this.addform.joinUserAccount.forEach((it) => {
          if (item.value == it) {
            name.push(item.label)
          }
        })
      })
      this.addform.joinUserName = this.addform.joinUserName.concat(name)
    },
    masterUserChange() {
      let name = []
      this.options.forEach((item) => {
        this.addform.masterUserAccount.forEach((it) => {
          if (item.value == it) {
            name.push(item.label)
          }
        })
      })
      this.addform.masterUserName = this.addform.masterUserName.concat(name)
    },
    cancelClose() {
      this.dialogVisible = false
      this.addform = this.$options.data().addform
      this.$refs.addform.resetFields()
    },

    // 成功失败日志
    logSuccessOrError(type) {
      this.addLog(
        0,
        this.elDialogTitle == '新增' ? 'add' : 'edit',
        this.addform,
        type
      )
    },

    sureAdd() {
      console.log(this.addform)
      this.$refs.addform.validate(async (valid) => {
        if (valid) {
          let res = {}
          let joinUserAccount = this.addform.joinUserAccount.join(',')
          let joinUserName = this.addform.joinUserName.join(',')
          let masterUserAccount = this.addform.masterUserAccount.join(',')
          let masterUserName = this.addform.masterUserName.join(',')
          if (this.elDialogTitle === '新增') {
            res = await add({
              ...this.addform,
              joinUserAccount,
              joinUserName,
              masterUserAccount,
              masterUserName
            })
          } else if (this.elDialogTitle === '编辑') {
            res = await edit({
              ...this.addform,
              joinUserAccount,
              joinUserName,
              masterUserAccount,
              masterUserName
            })
          } else {
            res = await copyMeetingConfig({
              ...this.addform,
              joinUserAccount,
              joinUserName,
              masterUserAccount,
              masterUserName
            })
          }
          if (res.code == 200) {
            this.cancelClose()
            this.$parent.search()
            // this.logSuccessOrError('success')
            this.$message.success(`${this.elDialogTitle}成功！`)
          } else {
            // this.logSuccessOrError('error')
            this.$message.error(res.data || `${this.elDialogTitle}失败！`)
          }
        } else {
          this.$message.error('请按要求填写表单！')
          return false
        }
      })
    },

    show(row, type) {
      if (row && row.id) {
        Object.assign(this.addform, row)
        this.addform.joinUserAccount =
          row.joinUserAccount?.length > 0 ? row.joinUserAccount.split(',') : []
        this.addform.joinUserName =
          row.joinUserName?.length > 0 ? row.joinUserName.split(',') : []
        this.addform.masterUserName =
          row.masterUserName?.length > 0 ? row.masterUserName.split(',') : []
        this.addform.masterUserAccount =
          row.masterUserAccount?.length > 0
            ? row.masterUserAccount.split(',')
            : []
      }
      this.elDialogTitle = type
      this.dialogVisible = true
    }
  }
}
</script>

<style></style>
